//
//  DDateManager.swift
//  Drop
//
//  Created by hushaohua on 2018/2/7.
//  Copyright © 2018年 init. All rights reserved.
//

import UIKit
import CoreData

class DDateManager{
    static let HTodayDidChangedNotification:String = "TodayDidChangedNotification";
    
    static let sharedInstance = DDateManager();
    class func sharedManager() -> DDateManager {
        return sharedInstance;
    }
    
    init() {
        
    }
    
    lazy var dayDateFormatter:DateFormatter = {
        var dateFormatter = DateFormatter();
        dateFormatter.dateFormat = "yyyy-MM-dd";
        return dateFormatter;
    }();
    
    var initDate:Date?;
    func markInitDate() -> Void{
        var date:Date? = UserDefaults.standard.object(forKey: "init_date") as? Date;
        if (date == nil){
            date = Date();
            UserDefaults.standard.set(date!, forKey: "init_date");
        }
        self.initDate = date;
        self.getEarilestDrop();
    }
    func initialDate() -> Date {
//        return Date(timeIntervalSince1970: 0);
        return UserDefaults.standard.object(forKey: "init_date") as! Date;
    }
    
    func getEarilestDrop() -> Void{
        let request:NSFetchRequest<NSDictionary> = NSFetchRequest(entityName: "Drop");
        request.resultType = .dictionaryResultType;
        request.propertiesToFetch = ["begin"];
        request.fetchLimit = 1;
        let sort = NSSortDescriptor(key: "begin", ascending: true);
        request.sortDescriptors = [sort];
        do{
            let infos = try HStoreManager.defaultManger().context.fetch(request);
            for drop in infos {
                let date:Date? = drop.object(forKey: "begin") as? Date;
                if (date != nil){
                    UserDefaults.standard.set(date!, forKey: "init_date");
                }
            }
        }catch{
            let nserror = error as NSError
            fatalError("tags controller fetch error \(nserror), \(nserror.userInfo)")
        }
        
    }
    
    func startedBefore() -> Bool{
        let date:Date? = UserDefaults.standard.object(forKey: "init_date") as? Date;
        return date != nil;
    }
    
    func startFirst() {
        self.markInitDate();
    }
    
    func start() -> Void {
        self.currentDay = Date();
        self.addNotifications();
        self.markInitDate();
    }
    
    var currentDay:Date?;
    func addNotifications() -> Void {
        let center = NotificationCenter.default;
        center.addObserver(self, selector: #selector(currentDayDidChanged(_:)), name: Notification.Name.NSCalendarDayChanged, object: nil);
        center.addObserver(self, selector: #selector(applicationDidEnterForeground(_:)), name: Notification.Name.UIApplicationDidEnterBackground, object: nil);
    }
    
    @objc func applicationDidEnterForeground(_ notification:NSNotification) -> Void{
        if (self.currentDay != nil && !Calendar.current.isDateInToday(self.currentDay!)){
            let notificationName = Notification.Name(DDateManager.HTodayDidChangedNotification);
            NotificationCenter.default.post(name: notificationName, object: nil);
        }
    }
    
    @objc func currentDayDidChanged(_ notification:Notification) -> Void{
        let notificationName = Notification.Name(DDateManager.HTodayDidChangedNotification);
        NotificationCenter.default.post(name: notificationName, object: nil);
    }
}
